package com.basker.pisces.orm.query;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.ArrayUtils;

import com.basker.pisces.core.query.ICriteria;
import com.basker.pisces.core.query.criteria.Criterion;
import com.basker.pisces.core.query.criteria.iterate.CriteriaIterator;
import com.basker.pisces.core.query.criteria.iterate.CriterionIterateArgs;
import com.basker.pisces.core.query.criteria.iterate.ICriteriaIterateHandler;
import com.basker.pisces.core.query.meta.QueryMeta;

class QueryParameterValueGenerator implements ICriteriaIterateHandler {

    public static Object[] genArgumentValue(QueryMeta queryMeta, List<Criterion> criteria) {
        CriteriaIterator iterator = new CriteriaIterator(queryMeta);
        QueryParameterValueGenerator generator = new QueryParameterValueGenerator();

        iterator.iterate(criteria, generator);

        return generator.values != null ? generator.values.toArray() : ArrayUtils.EMPTY_OBJECT_ARRAY;
    }

    private List<Object> values = new ArrayList<Object>();

    private QueryParameterValueGenerator() {

    }

    @Override
    public void beginIterate(CriterionIterateArgs args) {
        Criterion criterion = args.getCriterion();
        if (criterion instanceof ICriteria) {
            return;
        }

        Object value = criterion.getUpdateValue();

        if (value instanceof Object[]) {
            for (Object v : (Object[]) value) {
                this.addValue(criterion, v);
            }
        } else {
            this.addValue(criterion, value);
        }
    }

    private void addValue(Criterion criterion, Object value) {
        if ((!criterion.isParameterExpression())) {
            return;
        }

        if (Criterion.NO_CRITERION_VALUE.equals(value)) {
            return;
        }

        values.add(value);
    }

}
